#import "KwaiPlugin.h"

@interface KwaiPlugin ()

@property(nonatomic, strong) FlutterMethodChannel *channel;

@end

@implementation KwaiPlugin
+ (void)registerWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel
            methodChannelWithName:@"kwai"
                  binaryMessenger:[registrar messenger]];
    KwaiPlugin *instance = [[KwaiPlugin alloc] init];
    instance.channel = channel;
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([@"init" isEqualToString:call.method]) {
        [self handleInit:call];
        result(@"success");
    } else if ([@"authorLogin" isEqualToString:call.method]) {
        [self handleAuthorLogin:call];
        result(@"success");
    } else {
        result(FlutterMethodNotImplemented);
    }
}

/// 初始化快手SDK
- (void)handleInit:(FlutterMethodCall *)call {
    NSDictionary *args = call.arguments;
    NSString *apiKey = [args valueForKey:@"apiKey"];
    NSString *universalLink = [args valueForKey:@"link"];
    [KSApi registerApp:apiKey universalLink:universalLink delegate:self];
}

/// 授权快手登录
- (void)handleAuthorLogin:(FlutterMethodCall *)call {
    NSDictionary *args = call.arguments;
    NSString *scope = [args valueForKey:@"scope"];
    KSAuthRequest *request = [[KSAuthRequest alloc] init];
    request.scope = scope;
    [KSApi sendRequest:request completion:^(BOOL success) {
        NSLog(@"Send a request to login kwai：%d", success);
    }];
}

/// 回调信息
- (void)ksApiDidReceiveResponse:(KSBaseResponse *)response {
    // 处理来自快手终端的回应
    NSLog(@"Received a response from Kwai: %@", response);
    NSDictionary *result = @{
            @"code": @(response.error.code),
            @"msg": response.error.domain,
            @"data": response.state,
    };
    [self.channel invokeMethod:@"callback" arguments:result];
}

@end
